<template>
  <div class="chartview">
    <el-table
        class="custom-sort"
        :id="'tableDetail_'+uuid"
        :summary-method="getSummaries"
        :show-summary=summary
        :row-class-name="tableRowClassName"
        v-show="cType == 'table'"
        v-if="tableDataPage.length>0"
        :data="tableDataPage"
        border
        max-height="450"
        :default-sort="{ prop: sortColumn, order: 'ascending' }"
        :header-cell-style="mode=='light'?{ 'background-color': '#def2ff', color: '#333' }:{ 'background-color': '#def2ff', color: '#3A404F' }"
    >
      <el-table-column
          :sortable="units[item.column]?true:false"
          :prop="item.column"
          :label="item.fieldName+(units[item.column]?'('+units[item.column]+')':'')"
          v-for="(item, index) in chartData.header"
          :key="index"
      >
        <template #default="scope">
<!--          {{to_fiexd(scope.row[item.column])}}-->
          {{isFormatNumber(fieldcolumns[item.column]) ? to_fiexd(scope.row[item.column]) : scope.row[item.column]}}{{item.fieldClass}}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-if="pageInfo.total>pageInfo.pageSize&&cType == 'table'"
        v-model:current-page="pageInfo.currentPage"
        :page-size="pageInfo.pageSize"
        :small="true"
        :background="true"
        layout="total, prev, pager, next, jumper"
        :total="pageInfo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <div style="position:relative" v-if="this.chartData.latnResult">
      <div v-if="cType=='columnbar'&&this.chartData.latnResult.length>1" style="position:absolute;top:-39px;right:280px">指标:
        <el-select v-model="nowName" placeholder="请选择"  style="width:212px" @change="drawBarMapChart(nowName)">
          <el-option
              v-for="item in nameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <div v-show="cType != 'table'" ref="chart" :id="'chartdiv_'+uuid" :style="{ height: chartHeight + 'px' }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver' //下载exxel
import {v4 as uuidv4} from 'uuid';
import { shallowRef } from 'vue'
import consts from '../../common/consts'
import iconpg from '../../assets/images/web_tab_bg.png'
let echartsInstance={};
export default {
  setup() {
    //动态加载css
    let cssPath="";
    let mode=localStorage.getItem("mode")
    if(mode=="dark"){
      cssPath = import("/src/assets/css/dark/index.scss");
    }else if(mode=="light"){
      cssPath = import("/src/assets/css/light/index.scss");
    }
    return {
      cssPath
    };
  },
  props: {
    chartType: {
      type: String,
      require: false,
      default: 'bar'
    },
    chartData: {
      type: Object
    },
    sumCol:{
      type: Array,
    },
    units: {
      type: Object
    },
    fieldcolumns: {
      type: Object
    },
  },
  watch: {
    chartData: {
      handler(newVal) {
        this.dataSort();
      },
      deep: true // 开启深度监听
    }
  },
  data() {
    return {
      pageInfo:{
        currentPage:1,
        pageSize:30,
        total:0,
      },
      nowName:'',
      nameOptions:[],
      mode:localStorage.getItem("mode"),
      cType: 'bar', // 默认显示柱状图
      // echartsInstance: null,
      tableData: [],
      tableDataPage:[],
      tableHeader:[],
      chartHeight: 300, //
      wdData: [], //维度值
      jsData: [], //属性值
      label: {
        show: true,
        formatter: function (params) {
          // 判断数值是否超过10000，超过则显示为1万
          return params.value > 10000 ? params.value / 10000 + '万' : params.value
        }
      },
      summary:false,
      uuid:uuidv4(),
      echartsFieldColumn:{},
      echartsUnitY:'',
      echartsUnitX:'',
      lant_id_sort:consts.lant_id_sort,
      sortColumn:'',
      sums:[],
    }
  },
  created() {
    var len=this.chartData.data.length
    if(len>1&&Object.keys(this.chartData.data[0]).length>1&&this.sumCol.length>0){
      this.summary=true
    }
  },
  mounted() {
    this.cType = this.chartType
    this.initECharts()
    this.drawChart()
    //对数据重新排序
    this.dataSort();
    this.nameOptions = []
    if(this.chartData.latnResult){
      this.chartData.latnResult.forEach((e)=>{
        this.nameOptions.push(
          {
            label:e.name,
            value:this.chartData.latnResult.indexOf(e)
          }
        )
      })

    }
  },
  methods: {
    formatAmount(num) {
      return num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
    },
    tableRowClassName({
        row,
        rowIndex
      }) {
        if (rowIndex % 2 == 1) {
          return 'deep_row'
        } else {
          return 'light_row'
        }
      },
    handleSizeChange(val){},
    handleCurrentChange(val){
      this.pageInfo.currentPage=val
      this.tableDataPage=[]
      this.tableDataPage=this.tableData.slice((this.pageInfo.currentPage-1)*this.pageInfo.pageSize,this.pageInfo.currentPage*this.pageInfo.pageSize)
    },
    dataSort(){
      this.tableData=[]
      this.$props.chartData.data.forEach(item=>{
        if(item.LATN_ID){
          item.sort=this.lant_id_sort[item.LATN_ID]
        }
        this.tableData.push(item)
      })
      this.pageInfo.total=this.tableData.length
      //替换本地网ID
      this.$props.chartData.header.forEach(item=>{
        if(item.fieldName=="本地网ID") item.fieldName="本地网"
        if(this.pageInfo.total<=this.pageInfo.pageSize){
          if(item.column.startsWith("MONTH_ID")) this.sortColumn=item.column
          else if(item.column.startsWith("DAY_ID")) this.sortColumn=item.column
        }
      })
      this.tableData.sort(this.customSortMethod)
      this.$nextTick(()=>{
        this.tableDataPage=this.tableData.slice((this.pageInfo.currentPage-1)*this.pageInfo.pageSize,this.pageInfo.currentPage*this.pageInfo.pageSize)
      })
    },
    customSortMethod(a,b){
      if(a.sort < b.sort) {
        return -1; // a在b之前
      } else if(a.sort > b.sort) {
        return 1; // a在b之后
      } else {
        return 0; // 相等
      }
    },
    to_fiexd(val){
      // if(typeof val=='number'&&(val+"").indexOf(".")>-1){
      if(typeof val=='number'){
        // return val.toFixed(2)
        return this.formatAmount(val)
      }
      return val
    },
    getSummaries(param){
      const { columns, data } = param
      const sums = []
      console.log("this.sumCol====>",this.sumCol)
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }else if(this.sumCol.some(function(e) {return e==index})){
          let sum=0
          this.tableData.forEach(item=>{
            sum+=Number.isNaN(item[column.property])?0:Number(item[column.property])
          })
          sums[index]=this.to_fiexd(sum)
          // const values = data.map((item) => Number(item[column.property]))
          // if (!values.every((value) => Number.isNaN(value))) {
          //   sums[index] = `${values.reduce((prev, curr) => {
          //     const value = Number(curr)
          //     if (!Number.isNaN(value)) {
          //       return prev + curr
          //     } else {
          //       return prev
          //     }
          //   }, 0)}`
          //   if(parseFloat(sums[index])!='NaN'){
          //     sums[index]=this.to_fiexd(parseFloat(sums[index]))
          //   }
          // } else {
          //   sums[index] = 'N/A'
          // }
        }
      })
      return sums
    },
    exportExcel(){
      var vm=this;
      var setTime=1500
      // units[item.column]?'('+units[item.column]+')':'')
      let data = []
      let dataHeader=[]
      this.chartData.header.forEach(item=>{
        dataHeader.push(item.fieldName+(this.units[item.column]?'('+this.units[item.column]+')':''))
      })
      data.push(dataHeader)
      this.tableData.forEach(item=>{
        let dataInfo=[]
        Object.values(item).forEach(info=>{
          dataInfo.push(info)
        })
        data.push(dataInfo)
      })
      console.log("data====>",data)
      // 将数据转换为工作表
      const worksheet = XLSX.utils.aoa_to_sheet(data);

      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

      // 使用blob和FileReader创建一个URL然后下载
      try {
        const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        const savePromise = new Promise((resolve, reject) => {
          FileSaver.saveAs(new Blob([dataBlob], { type: 'application/octet-stream' }), '导出数据.xlsx', resolve('保存完成'));
        });
        savePromise.then((e) => {
          setTimeout(()=>{
            vm.$emit("backFun",false)
          },setTime)
        });
      }catch (e) {
        if (typeof console !== 'undefined') {}
      } finally {
        return excelBuffer
      }

      // this.pageInfo.pageSize=this.tableData.length
      // var userAgent=navigator.userAgent
      // var setTime=1500
      // var vm=this;
      // var xlsxParam = { raw: true }
      // var wb = XLSX.utils.table_to_book(
      //   document.querySelector('#tableDetail_'+this.uuid),
      //   xlsxParam
      // )
      // var wbout = XLSX.write(wb, {
      //   bookType: 'csv',
      //   bookSST: true,
      //   type: 'array',
      // })
      // try {
      //   let blob=new Blob([wbout], { type: 'application/octet-stream' })
      //   const savePromise = new Promise((resolve, reject) => {
      //     FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'data.csv', resolve('保存完成'));
      //   });
      //   savePromise.then((e) => {
      //     setTimeout(()=>{
      //       vm.$emit("backFun",false)
      //     },setTime)
      //   });
      // } catch (e) {
      //   if (typeof console !== 'undefined') {
      //   }
      // } finally {
      //   this.pageInfo.pageSize=30
      //   return wbout
      // }
    },
    deleteQg(str) {
      return str.replace(/\s*/g, '')
    },
    initECharts() {
      if (!echartsInstance[this.uuid]) {
        echartsInstance[this.uuid] = this.$echarts.init(document.getElementById('chartdiv_'+this.uuid))
        // this.echartsInstance = echarts.init(this.$refs.chart)
      }
    },
    drawChart() {
      // 根据当前图表类型绘制不同的图表
      switch (this.cType) {
        case 'bar':
          if(this.chartData.periodResult && this.chartData.periodResult.length > 0){
            this.drawBarChart()
          }else{
            this.drawBarChartOld()
          }
          break
        case 'columnbar':
          this.drawColumnBarChart()
          /*if(this.chartData.latnResult && this.chartData.latnResult.length > 0){
            this.nowName = 0
            this.drawBarMapChart(0)
          }else{
            this.drawColumnBarChart()
          }*/
          break
        case 'line':
          if(this.chartData.periodResult && this.chartData.periodResult.length > 0){
            this.drawLineChart()
          }else{
            this.drawLineChartOld()
          }
          break
        case 'pie':
          this.drawPieChart()
          // this.drawBarMapChart()
          break
        case 'radar':
          this.drawRadarChart()
          break
        // default:
        //   this.drawBarChart()
        //   break
      }
    },
    drawColumnBarChart() {
      // 绘制柱状图的示例数据和配置
      const { xArr, serArr } = this.transDataToChartData()
      const legendData = []
      var serises = []
      var vm=this
      for (var i = 0; i < xArr.length; i++) {
        var xdata = xArr[i]
        console.log("xdata=======>", xdata)
      }
      for (var i = 0; i < serArr.length; i++) {
        var sdata = serArr[i]
        var tp = {
          data: sdata,
          type: 'bar',
          barWidth: 20,
          // label: this.label,
          label: {
            show: true, //开启显示
            position: "right", //在上方显示
            formatter: function(params){
              // 判断数值是否超过10000，超过则显示为1万
              // return params.value > 10000 ? vm.to_fiexd(params.value / 10000) + '万' : vm.to_fiexd(params.value)
              return params.value > 10000 ? vm.to_fiexd(params.value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)
            },
            textStyle: {
              color: "#fff",
            },
            // textStyle: {
            //   //数值样式
            //   color: "#5C7CFF",
            //   // fontSize: this.fontSize(0.15),
            // },
            color: "#5C7CFF",
          },
        }
        serises.push(tp)
      }
      const option = {
        backgroundColor: {
          type: 'image',
          image: iconpg, // 背景图片的URL
          repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
          size: '100% 100%', // 图片大小，可以是数值或者百分比
          position: 'center center' // 图片位置，可以是数值或者百分比
        },
        color: ["#67ebfa", "#4487f0"],
        textStyle: {
          color: "#fff",
        },
        // title: {
        //   text: "World Population",
        // },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '10%',
          bottom: '8%',
          containLabel: true
        },
        dataZoom: [
          {
            // show: false,
            type: 'inside',
            realtime: true,
            yAxisIndex: 0,
            startValue: 0,
            endValue: xArr.length-1>5?5:xArr.length-1,
            bottom: '-25px',
          }
        ],
        xAxis: {
          name:this.echartsUnitY,
          type: 'value',
          boundaryGap: [0, 0.01],
          axisLine: {
            show: true
          },
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
            formatter: function (value) {
              // 判断数值是否超过10000，超过则显示为1万
              // return value > 10000 ? vm.to_fiexd(value / 10000) + '万' : vm.to_fiexd(value)
              return value > 10000 ? vm.to_fiexd(value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(value):value)
            }
          }
        },
        yAxis: {
          type: 'category',
          data: xArr,
          axisLabel: {
            textStyle: {
              color: "#fff",
            }
          }
        },
        series: serises
      }

      echartsInstance[this.uuid].setOption(option)
    },
    drawBarChart() {
      var vm=this
      const { xArr, serArr } = this.transDataToChartData()
      var xdata = []
      var ydata = []
      // var serName = ['派单客户数','高迁客户数']
      var serName = []
      var highNum = 0
      for (var i = 0; i < this.chartData.periodResult.length; i++) {
        xdata[i] = []
        ydata[i] = []
        serName[i] = this.chartData.periodResult[i].name
        this.chartData.periodResult[i].list.forEach((e)=>{
          if(e.flag==1){
            highNum = this.chartData.periodResult[i].list.indexOf(e)
          }
          xdata[i].push(e.name)
          ydata[i].push(e.value)
        })
      }
      var serises = []
      for (var i = 0; i < ydata.length; i++) {
        var sdata = ydata[i]
        var tp = {
          name:serName[i],
          data: sdata,
          markLine: {
              label: {
                show: true,
                position: "end",
                formatter: function(params){
                  // 判断数值是否超过10000，超过则显示为1万
                  // return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : vm.to_fiexd(params.value)
                  return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)
                },
                textStyle:{
                  color:'white'
                }
              },
              lineStyle: {
                width: 2,
                type: "dashed",
              },
              tooltip: {
                show:false,
              },
              data: [
                {
                  type: "average",
                },
              ],
            },
          type: 'bar',
          barWidth: 20,
          emphasis: {
              itemStyle: {
                  color: '#d5b913' // 高亮时的颜色
              }
          },
          // label: this.label,
          label: {
            show: true, //开启显示
            position: "top", //在上方显示
            formatter: function(params){
              // 判断数值是否超过10000，超过则显示为1万
              // return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : vm.to_fiexd(params.value)
              return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)
            },
            textStyle: {
              color: "#fff",
              fontSize:'8px'
            },
            color: "#5C7CFF",
          },
        }
        serises.push(tp)
      }
      // 绘制柱状图的示例数据和配置
      const option = {
        legend: {
          textStyle:{
            color:'white'
          }
        },
        tooltip: {
              trigger: 'item',
              formatter: "{a} : {c}"
          },
        backgroundColor: {
          type: 'image',
          image: iconpg, // 背景图片的URL
          repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
          size: '100% 100%', // 图片大小，可以是数值或者百分比
          position: 'center center' // 图片位置，可以是数值或者百分比
        },
        color: ["#284b91"],
        textStyle: {
          color: "#fff",
        },
        title: {
          // text: "2023年8月数据",
          left: 'center', // 表头水平居中
          // textStyle: {
          //   // 表头样式
          //   fontSize: 16,
          //   fontWeight: 'bold'
          // }
          fontSize: 16,
          fontWeight: 'bold'
        },
        dataZoom: [
          {
            // show: false,
            type: 'inside',
            realtime: true,
            startValue: 0,
            endValue: xdata[0].length-1>5?5:xdata[0].length-1,
            bottom: '-25px',
          }
        ],
        xAxis: {
          type: 'category',
          data: xdata[0],
          axisLabel: {
            textStyle: {
              color: "#fff",
            }
          }
        },
        yAxis: {
          name: this.echartsUnitY,
          type: 'value',
          axisLine: {
            show: true
          },
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
            formatter: function (value) {
              // 判断数值是否超过10000，超过则显示为1万
              // return value > 10000 ?vm.to_fiexd( value / 10000) + '万' : vm.to_fiexd(value)
              return value > 10000 ?vm.to_fiexd( value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(value):value)
            },
          }
        },
        series: serises
      }

      echartsInstance[this.uuid].setOption(option)

      for (var i = 0; i < this.chartData.periodResult.length; i++) {
        echartsInstance[this.uuid].dispatchAction({
            type: 'highlight',
            seriesIndex: i,
            dataIndex: highNum
        });
      }
    },
    drawLineChart() {
      var vm=this
      const { xArr, serArr } = this.transDataToChartData()
      var xdata = []
      var ydata = []
      // var serName = ['派单客户数','高迁客户数']
      var serName = []
      var highNum = 0
      for (var i = 0; i < this.chartData.periodResult.length; i++) {
        xdata[i] = []
        ydata[i] = []
        serName[i] = this.chartData.periodResult[i].name
        this.chartData.periodResult[i].list.forEach((e)=>{
          if(e.flag==1){
            highNum = this.chartData.periodResult[i].list.indexOf(e)
          }
          xdata[i].push(e.name)
          ydata[i].push(e.value)
        })
      }
      var serises = []
      for (var i = 0; i < ydata.length; i++) {
        var sdata = ydata[i]
        var tp = {
          name:serName[i],
          data: sdata, type: 'line',
          emphasis: {
              itemStyle: {
                  color: '#d5b913' // 高亮时的颜色
              }
          },
          // label: this.label,
          label: {
            show: true, //开启显示
            position: "top", //在上方显示
            formatter: function(params){
              // 判断数值是否超过10000，超过则显示为1万
              // return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : vm.to_fiexd(params.value)
              return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)
            },
            textStyle: {
              color: "#fff",
            },
            // textStyle: {
            //   //数值样式
            //   color: "#5C7CFF",
            //   // fontSize: this.fontSize(0.15),
            // },
            color: "#5C7CFF",
          },
        }
        serises.push(tp)
      }
      // 绘制折线图的示例数据和配置
      const option = {
        legend: {
          textStyle:{
            color:'white'
          }
        },
        tooltip: {
              trigger: 'item',
              formatter: "{a} : {c}"
          },
        backgroundColor: {
          type: 'image',
          image: iconpg, // 背景图片的URL
          repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
          size: '100% 100%', // 图片大小，可以是数值或者百分比
          position: 'center center' // 图片位置，可以是数值或者百分比
        },
        color: ["#284b91"],
        textStyle: {
          color: "#fff",
        },
        dataZoom: [
          {
            // show: false,
            type: 'inside',
            realtime: true,
            startValue: 0,
            endValue: xdata[0].length-1>5?5:xdata[0].length-1,
            bottom: '-25px',
          }
        ],
        xAxis: {
          type: 'category',
          data: xdata[0],
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
          }
        },
        yAxis: {
          name:this.echartsUnitY,
          type: 'value',
          axisLine: {
            show: true
          },
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
            formatter: function (value) {
              // 判断数值是否超过10000，超过则显示为1万
              // return value > 10000 ? value / 10000 + '万' : value
              return value > 10000 ? value / 10000 + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(value):value)
            }
          }
        },
        series: serises
      }

      echartsInstance[this.uuid].setOption(option)

      for (var i = 0; i < this.chartData.periodResult.length; i++) {
        echartsInstance[this.uuid].dispatchAction({
            type: 'highlight',
            seriesIndex: i,
            dataIndex: highNum
        });
      }
    },
    isFormatNumber(fieldColumn){
      var formatNumberFlag=false
      if ((fieldColumn.fieldClass == 1 || fieldColumn.fieldType == 4) && !fieldColumn.fieldCode.toUpperCase().startsWith("COUNT")){
        formatNumberFlag=true
      }
      return formatNumberFlag
    },
    drawRadarChart() {
      let vm=this;
      const { xArr, serArr } = this.transDataToChartData()
      var serises = []
      var maxVal=0;
      for (var i = 0; i < serArr.length; i++) {
        var sdata = serArr[i]
        maxVal=Math.max(...serArr[i])
        var tp = {
          value: sdata,
          label: {
            show: true, // 显示标签
            formatter: function (params) {
              // return vm.to_fiexd(params.value)+''+(vm.echartsUnitY ? vm.dataAnalysis : "") // 显示数值
              return (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)+''+(vm.echartsUnitY ? vm.echartsUnitY : "") // 显示数值
            },
            // textStyle: {
            //   //数值样式
            //   color: "#5C7CFF",
            // },
            textStyle: {
              color: "#fff",
            },
            color: "#5C7CFF",
          }
        }
        serises.push(tp)
      }
      var idg = []
      for (var i = 0; i < xArr.length; i++) {
        idg.push({ name: xArr[i] ,max:maxVal})
      }
      // 绘制雷达图的示例数据和配置
      const option = {
        backgroundColor: {
          type: 'image',
          image: iconpg, // 背景图片的URL
          repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
          size: '100% 100%', // 图片大小，可以是数值或者百分比
          position: 'center center' // 图片位置，可以是数值或者百分比
        },
        color: ["#5C7CFF"],
        tooltip: {
          trigger: 'item',
        },
        radar: {
          indicator: idg,
          nameGap:-10,//指示器名称和指示器轴的距离,默认15
          center: ['50%', '50%'],//雷达图的中心位置
          radius: '85%',// 半径
          splitNumber: 5, // 分隔段数, 默认5
          shape: 'circle', // 雷达图绘制类型: 'polygon'(默认) / 'circle'
        },
        series: [
          {
            name: '指标值',
            type: 'radar',
            data: serises
          }
        ]
      }

      echartsInstance[this.uuid].setOption(option)
    },
    drawPieChart() {
      let vm=this
      const { xArr, serArr } = this.transDataToChartData()
      var serises = serArr[0]

      var dataTp = []
      for (var i = 0; i < xArr.length; i++) {
        // var tepobj = { value: vm.to_fiexd(serises[i]), name: xArr[i] }
        var tepobj = { value: (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(serises[i]):serises[i]), name: xArr[i] }
        dataTp.push(tepobj)
      }
      const option = {
        backgroundColor: {
          type: 'image',
          image: iconpg, // 背景图片的URL
          repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
          size: '100% 100%', // 图片大小，可以是数值或者百分比
          position: 'center center' // 图片位置，可以是数值或者百分比
        },
        // title: {
        //   text: "Referer of a Website",
        //   subtext: "Fake Data",
        //   left: "center",
        // },

        color: ["#67ebfa","#4487f0"],
        tooltip: {
          trigger: 'item',
          formatter: `{b} : {c}${this.echartsUnitY} ({d}%)`

        },
        legend: {
          orient: 'vertical',
          left: 'left',
          textStyle: {
            color: "#ffffff"
          },
        },
        series: [
          {
            // name:this.echartsUnitY,
            type: 'pie',
            radius: '70%',
            data: dataTp,
            label: {
              show: true,
              position: "outside",
              color: "#fff",
              fontSize: 12,
            },
            labelLine: {
              show: true,
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          },
          {
            // name:this.echartsUnitY,
            type: 'pie',
            radius: '70%',
            data: dataTp,
            label: {
              show: true,
              position: "inside",
              formatter: `{d}%`,
              // textStyle: {
              //   //数值样式
              //   color: "#fff",
              // },
              color: "#fff",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }

      echartsInstance[this.uuid].setOption(option)
    },
    drawBarMapChart(index){
      var vm=this
      // var uploadedDataURL = "../anhui.json"
      var ppdata = []
      var yname = [];
      var highNum = null
      this.chartData.latnResult[index].list.forEach((e)=>{
        ppdata.push(
          {
            name:e.name,
            value:e.value
          }
        )
        yname.push(e.name)
        if(e.flag==1){
          highNum = this.chartData.latnResult[index].list.indexOf(e)
        }
      })
      var seriesdata = [
          //人口
          {
              name: '',
              type: 'map',
              map: '安徽',
              label:{
                color:'white'
              },
              itemStyle: {
                  normal: {
                      label: {
                          show: true,
                          color:'white',
                      },
                      emphasis: {
                          label: {
                              show: true
                          }
                      }
                  }
              },
              data: ppdata
          },

          //右边图表人口
          {
              name: '',
              type: 'bar',
              xAxisIndex: 0,
              yAxisIndex: 0,
              // barWidth: '15%',
              barWidth: 5,
              itemStyle: {
                  normal: {
                      color: 'white'
                  },
              },
              emphasis: {
                  itemStyle: {
                      color: '#d5b913' // 高亮时的颜色
                  }
              },
              label: {
                  normal: {
                      show: true,
                      position: "right",
                      textStyle: {
                          color: "white"
                      },
                      formatter: function(params){
                        // 判断数值是否超过10000，超过则显示为1万
                        // return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : vm.to_fiexd(params.value)
                        return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)
                      },
                  },
              },
              data: ppdata
          },
      ];
      //人口
      var option ={
          width:200,
          height:250,
          grid: {
              left: '10%',    // 距离左侧的距离可以是百分比或像素值
              top: '10%',     // 距离顶部的距离
              right: '20%',   // 距离右侧的距离
              bottom:'10%'
          },
          backgroundColor: {
              type: 'image',
              image: iconpg, // 背景图片的URL
              repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
              size: '100% 100%', // 图片大小，可以是数值或者百分比
              position: 'center center' // 图片位置，可以是数值或者百分比
          },
          title: {
              text: '',
              subtext: '',
              left: 'center',
              textStyle: {
                  color: '#000'
              }
          },
          tooltip: {
              trigger: 'item',
              formatter: "{b} : {c}"
          },
          visualMap: {
            min: 10000,
            max: 30000,
            right: '10%',
            top: 'bottom',
            text: ['高', '低'],
            textStyle: {
              color: 'white',
            },
            // calculable: true,
            // colorLightness: [0.8, 100],
            color: ['#072666' , '#7ca9ff'],
            dimension: 0,
          },


          xAxis: {
              gridIndex: 0,
              axisTick: {
                  show: false
              },
              axisLabel: {
                  show: false
              },
              splitLine: {
                  show: false
              },
              axisLine: {
                  show: false
              }
          },
          yAxis: {
              axisLabel: {
                show: true,
                textStyle: {
                  color:'white'  //这里用参数代替了
                },
              },
              data: yname,
          },
          series: seriesdata
      };
      fetch("./anhui.json")
      .then(response => response.json())
      .then(res => {
        var gdMap = res;
        console.log(gdMap,'gdMapgdMap');
        echarts.registerMap('安徽', gdMap);
        echartsInstance[this.uuid].setOption(option,true)
        echartsInstance[this.uuid].dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: highNum
        })
        echartsInstance[this.uuid].dispatchAction({
          type: 'highlight',
          seriesIndex: 1,
          dataIndex: highNum
      });
      })
      // const response = fetch(uploadedDataURL);
      // this.gdMap = response.json();
      // console.log(gdMap,'gdMapgdMap');
      // echarts.registerMap('安徽', gdMap);
      // echartsInstance[this.uuid].setOption(option,true)
    //   axios.request({
    //     url: uploadedDataURL,
    // }).then((gdMap)=>{
    //   console.log(gdMap,'ggggggggggg');
    //   echarts.registerMap('安徽', gdMap);
    //     echartsInstance[this.uuid].setOption(option,true)
    // })

      // $.get(uploadedDataURL, function(gdMap) {
      //     echarts.registerMap('安徽', gdMap);
      //     // myChart.setOption(option, true);
      //     echartsInstance[this.uuid].setOption(option,true)
      // });
      // echartsInstance[this.uuid].setOption(option)
    },

    switchChart(type) {
      this.cType = type
      echartsInstance[this.uuid].clear() //

      this.$nextTick(() => {
        this.initECharts()
        this.drawChart()
      })
    },
    //将数据源转成chartData类型
    transDataToChartData() {
      const { data, header } = this.chartData
      var foundhobj = {}
      var foundhobjList=[]
      for (var i = 0; i < header.length; i++) {
        var sbitem = header[i]
        if (sbitem.valueT === 'N') {
          var sbkey = sbitem.column
          var fisrtV = data.length > 0 ? data[0][sbkey] : null
          var areAllEqual = data.every((item) => item[sbkey] === fisrtV)
          if (!areAllEqual||data.length==1) {
            foundhobj = sbitem
            foundhobjList.push(sbitem)
          }
        }
      }
      var xv = foundhobj.column
      var xArr = data.map((item) => item[xv])
      if (!xv){
        xArr = [header[0].column];
      }
      var columnsWithT = header.filter((item) => item.valueT === 'T').map((item) => item.column)
      var serArr = []
      this.echartsUnitY=this.units[columnsWithT]
      this.echartsFieldColumn=this.fieldcolumns[columnsWithT]
      for (var i = 0; i < columnsWithT.length; i++) {
        var ct = this.deleteQg(columnsWithT[i])
        var tempct = data.map((item) => item[ct])
        serArr.push(tempct)
      }
      return { xArr, serArr }
    },


    drawBarChartOld() {
      var vm=this
      const { xArr, serArr } = this.transDataToChartData()
      var serises = []
      for (var i = 0; i < serArr.length; i++) {
        var sdata = serArr[i]
        var tp = {
          data: sdata,
          type: 'bar',
          barWidth: 20,
          // label: this.label,
          label: {
            show: true, //开启显示
            position: "top", //在上方显示
            formatter: function(params){
              // 判断数值是否超过10000，超过则显示为1万
              // return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : vm.to_fiexd(params.value)
              return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)
            },
            textStyle: {
              color: "#fff",
            },
            // textStyle: {
            //   //数值样式
            //   color: "#5C7CFF",
            //   // fontSize: this.fontSize(0.15),
            // },
            color: "#5C7CFF",
          },
        }
        serises.push(tp)
      }
      // 绘制柱状图的示例数据和配置
      const option = {
        backgroundColor: {
          type: 'image',
          image: iconpg, // 背景图片的URL
          repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
          size: '100% 100%', // 图片大小，可以是数值或者百分比
          position: 'center center' // 图片位置，可以是数值或者百分比
        },
        color: ["#67ebfa"],
        textStyle: {
          color: "#fff",
        },
        title: {
          // text: "2023年8月数据",
          left: 'center', // 表头水平居中
          // textStyle: {
          //   // 表头样式
          //   fontSize: 16,
          //   fontWeight: 'bold'
          // }
          fontSize: 16,
          fontWeight: 'bold'
        },
        dataZoom: [
          {
            // show: false,
            type: 'inside',
            realtime: true,
            startValue: 0,
            endValue: xArr.length-1>5?5:xArr.length-1,
            bottom: '-25px',
          }
        ],
        xAxis: {
          type: 'category',
          data: xArr,
          axisLabel: {
            textStyle: {
              color: "#fff",
            }
          }
        },
        yAxis: {
          name: this.echartsUnitY,
          type: 'value',
          axisLine: {
            show: true
          },
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
            formatter: function (value) {
              // 判断数值是否超过10000，超过则显示为1万
              // return value > 10000 ?vm.to_fiexd( value / 10000) + '万' : vm.to_fiexd(value)
              return value > 10000 ?vm.to_fiexd( value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(value):value)
            },
          }
        },
        series: serises
      }

      echartsInstance[this.uuid].setOption(option)
    },
    drawLineChartOld() {
      var vm=this
      const { xArr, serArr } = this.transDataToChartData()
      var serises = []
      for (var i = 0; i < serArr.length; i++) {
        var sdata = serArr[i]
        var tp = {
          data: sdata, type: 'line',
          // label: this.label,
          label: {
            show: true, //开启显示
            position: "top", //在上方显示
            formatter: function(params){
              // 判断数值是否超过10000，超过则显示为1万
              // return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : vm.to_fiexd(params.value)
              return params.value > 10000 ?  vm.to_fiexd(params.value / 10000) + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(params.value):params.value)
            },
            textStyle: {
              color: "#fff",
            },
            // textStyle: {
            //   //数值样式
            //   color: "#5C7CFF",
            //   // fontSize: this.fontSize(0.15),
            // },
            color: "#5C7CFF",
          },
        }
        serises.push(tp)
      }
      // 绘制折线图的示例数据和配置
      const option = {
        backgroundColor: {
          type: 'image',
          image: iconpg, // 背景图片的URL
          repeat: 'repeat-x', // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
          size: '100% 100%', // 图片大小，可以是数值或者百分比
          position: 'center center' // 图片位置，可以是数值或者百分比
        },
        color: ["#5C7CFF"],
        textStyle: {
          color: "#fff",
        },
        dataZoom: [
          {
            // show: false,
            type: 'inside',
            realtime: true,
            startValue: 0,
            endValue: xArr.length-1>5?5:xArr.length-1,
            bottom: '-25px',
          }
        ],
        xAxis: {
          type: 'category',
          data: xArr,
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
          }
        },
        yAxis: {
          name:this.echartsUnitY,
          type: 'value',
          axisLine: {
            show: true
          },
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
            formatter: function (value) {
              // 判断数值是否超过10000，超过则显示为1万
              // return value > 10000 ? value / 10000 + '万' : value
              return value > 10000 ? value / 10000 + '万' : (vm.isFormatNumber(vm.echartsFieldColumn)?vm.to_fiexd(value):value)
            }
          }
        },
        series: serises
      }

      echartsInstance[this.uuid].setOption(option)
    },


  }
}
</script>

<style lang="scss" scoped>
/* 可以根据需要添加样式 */
.chartview {

  width: 100%;
  //max-height: 480px;
}
//  /deep/ 为深度操作符，可以穿透到子组件
:deep(.el-table) {
  display: flex;
  flex-direction: column;
}

//  order默认值为0，只需将表体order置为1即可移到最后，这样合计行就上移到表体上方
:deep(.el-table__body-wrapper) {
  order: 1;
}
// //  /deep/ 为深度操作符，可以穿透到子组件
// :deep(.el-table) {
//   display: flex;
//   flex-direction: column;
// }

// //  order默认值为0，只需将表体order置为1即可移到最后，这样合计行就上移到表体上方
// :deep(.el-table__body-wrapper) {
//   order: 1;
// }

//@import './index.css';
::v-deep .el-table__footer-wrapper tfoot td.el-table__cell {
  background-color: #b3b4b4 !important; /* 合计行背景色 */
  color: #ffffff!important; /* 合计行字体颜色 */
}
::v-deep .el-table td.el-table__cell div {
  font-size: 12px;
  color: #333;
  opacity: 0.9;
}
::v-deep .el-table th.el-table__cell.is-leaf,
::v-deep .el-table td.el-table__cell {
  border: 1px solid transparent !important;
}
::v-deep .el-table {
  tbody tr {
    &:hover {
      td {
        background-color: rgba($color: #81D3F8, $alpha: 0.5) !important;
      }
    }
  }
}
::v-deep .deep_row {
  background: #cfcfd0 !important;
}

::v-deep .light_row {
  background: rgba(255,255,255,0.1) !important;
}
</style>
